package xyz.robinbingo.dailybill.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.robinbingo.dailybill.dto.BillListDto;
import xyz.robinbingo.dailybill.dto.SumDto;
import xyz.robinbingo.dailybill.entity.BillDetail;
import xyz.robinbingo.dailybill.mapper.BillDetailMapper;
import xyz.robinbingo.dailybill.service.BillDetailService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BillDetailServiceImpl
 *
 * @author Robin
 * @date 2019/1/8 17:58
 **/
@Service
public class BillDetailServiceImpl extends ServiceImpl<BillDetailMapper, BillDetail> implements BillDetailService {

    /**
     * 列出指定日期的账单详情
     *
     * @param date 统计日期
     * @return List
     * @author Robin
     * @date 2019/1/9 14:07
     **/
    @Override
    public List<BillListDto> billList(String date) {
        Map<String, String> condition = getConditionMap(date);
        return getBaseMapper().getBillList(condition);
    }

    /**
     * 统计指定时间的收入和支出
     *
     * @param date 统计日期
     * @return JSONObject
     * @author Robin
     * @date 2019/1/9 15:34
     **/
    @Override
    public JSONObject sum(String date) {
        JSONObject total = new JSONObject(2);

        Map<String, String> condition = getConditionMap(date);

        List<SumDto> list = getBaseMapper().getSumByMonth(condition);
        list.forEach(object -> {
            Boolean type = object.getIo();
            BigDecimal sum = object.getSum();
            if (type) {
                total.put("income", sum);
            } else {
                total.put("outcome", sum);
            }
        });

        return total;
    }

    private Map<String, String> getConditionMap(String date) {
        Date selected;
        if (StrUtil.isBlank(date)) {
            selected = new Date();
        } else {
            selected = DateUtil.parse(date, "yyyy-MM").toJdkDate();
        }
        String start = DateUtil.beginOfMonth(selected).toDateStr();
        String end = DateUtil.endOfMonth(selected).toDateStr();
        Map<String, String> condition = new HashMap<>(2);
        condition.put("start", start);
        condition.put("end", end);
        return condition;
    }
}
